package com.face.server.controller;

import com.face.RespMsg;
import com.face.server.entity.Admin;
import com.face.server.repository.ApplyRepository;
import com.face.server.service.ApplyService;
import com.util.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.List;

/**
 * Created by ryan on 2018/3/27.
 */
@RestController
@RequestMapping("/apply")
public class ApplyController {
    @Autowired
    ApplyRepository applyRepository;

    @Autowired
    ApplyService applyService;

    @GetMapping("/list")
    RespMsg list(@PageableDefault(sort = "status",direction = Sort.Direction.ASC) Pageable pageable,
                 @RequestParam(defaultValue = "0000-00-00") String begin,
                 @RequestParam(defaultValue = "9999-99-99") String end,
                 @RequestParam(defaultValue = "") String input) throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        Admin admin = (Admin) subject.getPrincipal();
        if (admin.isSuper()==false) {
            List<Integer> dormitoryNumList=admin.getDormitoryNumList();
            return applyService.listMy(pageable, DateUtils.parse(begin), DateUtils.parse(end), input, dormitoryNumList);
        }
        return applyService.list(pageable,DateUtils.parse(begin), DateUtils.parse(end),input);
    }

    @GetMapping("/listMy")
    RespMsg listMy(@PageableDefault(sort = "status",direction = Sort.Direction.ASC) Pageable pageable,
                 @RequestParam(defaultValue = "0000-00-00") String begin,
                 @RequestParam(defaultValue = "9999-99-99") String end,
                 @RequestParam(defaultValue = "") String input) throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        Admin admin = (Admin) subject.getPrincipal();
        List<Integer> dormitoryNumList=admin.getDormitoryNumList();
        if (admin.isSuper()==true)
            return applyService.list(pageable,DateUtils.parse(begin), DateUtils.parse(end),input);
        return applyService.listMy(pageable,DateUtils.parse(begin), DateUtils.parse(end),input,dormitoryNumList);
    }

    @GetMapping("/findOne/{id}")
    RespMsg findOne(@PathVariable String id){
        return RespMsg.build(applyRepository.findOne(id));
    }


}
